package api

import (
	"bilibi.com/comment/conf"
	"bilibi.com/comment/model"
	"context"
	"google.golang.org/grpc"
	"time"
)

// 需要在GOPATH下运行
//go:generate protoc --go_out=plugins=grpc:. bilibi.com/comment/api/api.proto
//go:generate protoc --gofast_out=. bilibi.com/comment/model/comment.proto

func New(c *conf.Config) (*GRPCCommentClient, error) {
	conn, err := grpc.Dial(c.CommentRPCAddr, grpc.WithInsecure())
	if err != nil {
		panic(err)
	}

	client := NewCommentClient(conn)
	return &GRPCCommentClient{client: client}, nil
}

type GRPCCommentClient struct {
	client CommentClient
}

func (c GRPCCommentClient) UpdateComment(id int64, name string, message string, top int8) (err error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	_, err = c.client.UpdateComment(ctx, &UpdateCommentReq{Id: id, Name: name, Message: message, Top: int32(top)})
	return
}

func (c GRPCCommentClient) GetComment(id int64) (res *model.Comment, err error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	reply, err := c.client.GetComment(ctx, &GetCommentReq{Id: id})
	if err != nil {
		return nil, err
	} else {
		return reply.Res, err
	}
}
